package com.zhiche.lisa.integration.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * lisa-op 日志拦截处理
 */
@Aspect
@Component
public class OpLoggerInterceptorHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private long startTimeMillis = 0L;

    @Pointcut("execution(public * com.zhiche..*.*Controller.*(..))")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        startTimeMillis = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String clazzName = joinPoint.getTarget().getClass().getName();
        logger.info("LOGGER [           INFO]  ip:{} controller:{}  uri:{}  --[   start]", ip, clazzName, uri);
    }

    @After("log()")
    public void doAfter(JoinPoint joinPoint) {
        long endTimeMillis = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        String ip = request.getRemoteAddr();
        String clazzName = joinPoint.getTarget().getClass().getName();
        long methodTime = startTimeMillis - endTimeMillis;
        logger.info("LOGGER [           INFO]   ip:{} controller:{} method:{}  spendTime:{}---[    end]", ip, clazzName, uri, methodTime);
    }

}
